<!--
 * @Author: wuyuxin
 * @Date: 2022-02-12 17:32:02
 * @LastEditors: wuyuxin
 * @LastEditTime: 2022-02-12 17:38:18
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <button id="connect">连接</button>
  <button id="send" disabled="true">发送数据</button> <br>
  从服务端接收的数据如下: <br>
  <span id="recv"></span>
  <script>
    var connect = document.querySelector('#connect')
    var send = document.querySelector('#send')
    var recv = document.querySelector('#recv')
    let ws = null
    connect.onclick = function() {
      ws = new WebSocket('ws://localhost:9998')
      ws.onopen = () => {
        console.log('连接成功')
        send.disabled = false
      }
      ws.onclose = () => {
        console.log('连接失败')
        send.disabled = true
      }
      ws.onmessage = (msg) => {
        console.log('接收到从服务端发送过来的数据了')
        recv.innerHTML = msg.data
      }
    }

    send.onclick = function() {
      ws.send('helloSocket')
    }
  </script>
</body>
</html>